﻿using System;
using System.Linq;
using System.Threading;

namespace SopCastRecorder
{
	public class SopCastPlayer : SopCastBase
	{
		public static int RecordButtonIndex = OptionFile.Option1.SopCastPlayerRecordButtonIndex;
		private IntPtr RecordButtonHandle
		{
			get
			{
				return this.ButtonHandles[RecordButtonIndex];
			}
		}

		public static SopCastPlayer GetInstance(IntPtr[] hWnds, SopCastBody body)
		{
			for (var i = 0; i < hWnds.Length; i++)
			{
				var sopCastPlayer1 = SopCastPlayer.GetInstance2(hWnds[i], body);
				if (sopCastPlayer1 != null)
				{
					return sopCastPlayer1;
				}
			}
			return null;
		}
		private static SopCastPlayer GetInstance2(IntPtr playerHandle, SopCastBody body)
		{
			var player = new SopCastPlayer()
			{
				MainHandle = playerHandle
			};

			if (!player.CheckRect(body))
			{
				return null;
			}

			player.RefreshHandle();

			if (!player.CheckHandle())
			{
				return null;
			}
			return player;
		}
		private bool CheckRect(SopCastBody body)
		{
			var bodyRect = body.GetRect();
			var playerRect = this.GetRect();
			return
				bodyRect.right == playerRect.left &&
				bodyRect.top < playerRect.top && playerRect.top < bodyRect.bottom;
		}
		protected override bool CheckHandle()
		{
			if (this.ButtonHandles.Count() <= RecordButtonIndex)
			{
				return false;
			}
			return true;
		}

		public void ClickRecordButton()
		{
			var befores = Win32Api.GetHandles();
			new Thread(new ThreadStart(() =>
			{
				Win32Api.Click(this.RecordButtonHandle);
			})).Start();
			while (true)
			{
				var newProcess = SopCast.GetNewProcess(befores);
				var sopCastDialog1 = SopCastSaveDialog.GetInstance(newProcess);

				if (sopCastDialog1 == null)
				{
					Thread.Sleep(100);
				}
				else
				{
					this.SopCast1.SopCastSaveDialog1 = sopCastDialog1;
					this.SopCast1.SopCastSaveDialog1.SopCast1 = this.SopCast1;
					break;
				}
			}
		}

		public void ClickStopButton()
		{
			new Thread(new ThreadStart(() =>
			{
				Win32Api.Click(this.RecordButtonHandle);
			})).Start();
		}
	}
}
